package com.example.otto.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.otto.DTO.ManagerLoginDTO;
import com.example.otto.DTO.UserLoginDTO;
import com.example.otto.entity.Manager;
import com.example.otto.entity.Task;
import com.example.otto.entity.User;
import com.example.otto.mapper.UserMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public int save(User user){
        if (user.getId()==null){
            return userMapper.insert(user);
        }else {
            return userMapper.update(user);
        }
    }

    public ResponseEntity<?> loginService(User user) {
        User result = userMapper.login(user.getUsername(),user.getPassword());
        if (result != null) {
            String secretKey = "123456";
            long ttlMills = 3600000L;
            Map<String,Object> claims = new HashMap<>();
            claims.put("username", result.getUsername());

            // 生成JWT token
            String token = Jwts.builder()
                    .setClaims(claims) // 设置payload
                    .setExpiration(new Date(System.currentTimeMillis() + ttlMills)) // 设置过期时间
                    .signWith(SignatureAlgorithm.HS256, secretKey) // 使用HS256算法和密钥签名
                    .compact(); // 压缩成一个字符串，这就是最终的JWT token

            UserLoginDTO userLoginDTO = new UserLoginDTO(result,token);

            return ResponseEntity.ok(userLoginDTO); // 或者返回其他自定义的DTO
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }


}
